package com.huawang.mdesign.model.service.request;

import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import java.util.List;
import java.util.Objects;

/**
 * @author zcc
 * @description
 * @date 2024/3/15
 */
@Data
public class InstanceInfoDTO {
    @Schema(title = "属性Id")
    private String propertyId;
    @Schema(title = "属性名称")
    private String propertyName;
    @Schema(title = "设置的类型Id")
    private String typeId;
    @Schema(title = "设置的Values")
    private Object values;
    @Schema(title = "子实例列表")
    private List<InstanceInfoDTO> children;

    @JsonIgnore
    private transient int level;

    /**
     * 实例名称生成器
     */
    private InstanceNameGenerator instanceNameGenerator = new InstanceNameGenerator();

    @JsonIgnore
    public String getInstanceNamePath() {
        return instanceNameGenerator.getInstanceNamePath();
    }

    public void setOrder(Integer order) {
        this.instanceNameGenerator.setOrder(order);
    }

    @Data
    public class InstanceNameGenerator {
        private String instanceNamePath;
        private String instanceName;
        private Integer order;

        public void init(InstanceInfoDTO parent) {
            // 设置路径
            StringBuilder builder = new StringBuilder();
            if (Objects.nonNull(parent.getInstanceNamePath())) {
                builder.append(Objects.nonNull(parent.getInstanceNamePath()) ? parent.getInstanceNamePath() : "")
                        .append(".");
            }
            builder.append(Objects.nonNull(parent.getPropertyName()) ? parent.getPropertyName() : "");
            this.setInstanceNamePath(builder.toString());
            // 设置新实例名
            if (Objects.nonNull(this.getOrder())) {
                this.setInstanceName(propertyName + "[" + this.getOrder() + "]");
            } else {
                this.setInstanceName(propertyName);
            }
        }

        public String generateInstanceName() {
            StringBuilder defaultInstanceNameBuilder = new StringBuilder();
            if (Objects.nonNull(this.getInstanceNamePath())) {
                defaultInstanceNameBuilder.append(instanceNamePath).append(".");
            }
            defaultInstanceNameBuilder.append(Objects.nonNull(instanceName) ? instanceName : propertyName);
            return defaultInstanceNameBuilder.toString();
        }
    }
}
